package com.framework.dubbo.producer.file2html;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReader;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用hutool处理csv
 * @author xianggj
 * @Date 2021/5/20 10:58
 **/
public class CsvUtils {
    
    public static List<Map<String, Object>> getCsvData(InputStream in){
        List<Map<String, Object>> resList = new ArrayList<>();
        CsvReader csvReader = CsvUtil.getReader();
        byte[] buffer = IoUtil.readBytes(in);
        String encode = FileEncodeUtil.getJavaEncode(buffer);
        InputStream inputStream = new ByteArrayInputStream(buffer);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName(encode));
        CsvData read = csvReader.read(inputStreamReader);
        int rowCount = read.getRowCount();
        List<CsvRow> rows = read.getRows();
        //默认当第一行为列名
        CsvRow headerRow = rows.get(0);
        int fieldCount = headerRow.getFieldCount();
        List<String> headList = headerRow.getRawList();
        if (headList == null || headList.size() == 0){
            return resList;
        }
        Map<String, Object> headMap = new HashMap<>();
        for (int i = 0; i < headList.size(); i++) {
            String column = headList.get(i);
            headMap.put(column, i);
        }
        resList.add(headMap);
        String[] headers = headList.toArray(new String[fieldCount]);
        for (int i = 1; i < rowCount; i++) {
            Map<String, Object> map = new HashMap<>();
            CsvRow csvRow = rows.get(i);
            List<String> rawList = csvRow.getRawList();
            if (rawList.size() > fieldCount){
                continue;
            }
            for (int j = 0; j < rawList.size() ; j++) {
                map.put(headers[j], rawList.get(j));
            }
            resList.add(map);
        }
        return resList;
    }

}
